<!--
 * 组织/职务 导入Excel
 *
 * @author tqfeiyang
 * @since 2024-09-19
-->
<template>
  <a-modal v-model:open="visible" title="导入职务" @ok="closeModal" @onCancel="closeModal" destroyOnClose
    okText="关闭"
    okType="default"
    :cancel-button-props="{style: {display: 'none'}}"
    >
    <div style="text-align: center; width: 400px; margin: 0 auto">
        <a-button @click="downloadTemplate"> <download-outlined />第一步：下载模板</a-button>
        <br />
        <br />
        <a-upload
          v-model:fileList="fileList"
          name="file"
          :multiple="false"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
          @remove="handleRemove"
        >
          <a-button>
            <upload-outlined />
            第二步：选择文件
          </a-button>
        </a-upload>

        <br />
        <a-button @click="importExcel">
          <ImportOutlined />
          第三步：开始导入
        </a-button>
      </div>
  </a-modal>
  </template>
  
  <script setup>
    import { reactive, ref, nextTick } from 'vue';
    import { message } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { smartSentry } from '/@/lib/smart-sentry';
    import { positionApi } from '/@/api/business/organization/position-api';
  
  // ---------------- 对外暴漏 --------------------

  defineExpose({ showModal });

  const emits = defineEmits(['refresh']);

  // ---------------- 显示/关闭 -------------------

  const visible = ref(false);
  const fileList = ref([]);

  function showModal() {
    fileList.value = []
    visible.value = true;
  }

  function closeModal() {
    visible.value = false;
  }

  // ---------------- 上传/下载 -------------------

  async function downloadTemplate() {
    await positionApi.downloadPositionTemplate();
  }

  function handleRemove(file) {
    console.log('handleRemove', file)
    const index = fileList.value.indexOf(file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
  }

  function beforeUpload(file) {
    console.log('beforeUpload', file)
    fileList.value = [...(fileList.value || []), file];
    return false;
  }

async function importExcel() {
  const formData = new FormData();
  fileList.value.forEach((file) => {
    formData.append('file', file.originFileObj);
  });
  try {
    SmartLoading.show();
    const res = await positionApi.importPositionsFromExcel(formData);
    message.success(res.message);
    emits('refresh');
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
  </script>
  
  <style lang="less" scoped>
  </style>
  